package com.zymail.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zymail.bean.ZyAdmin;
import com.zymail.bean.ZyUser;
import com.zymail.entity.WechatModel;
import com.zymail.service.ZyAdminService;
import com.zymail.service.ZyUserService;
import com.zymail.url.HttpSender;
import com.zymail.util.MyJsonTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashMap;

import static com.zymail.entity.WXCore.decrypt;
import static com.zymail.entity.WechatConstant.APPID;
import static com.zymail.entity.WechatConstant.APPSECRET;

@RestController
public class LoginController extends BaseController {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ZyUserService userService;

    @Autowired
    private ZyAdminService adminService;

    @PostMapping("/login")
    public String Login(@RequestBody WechatModel wechatModel) throws IOException {
        HashMap<String,String> requestUrlParam = new HashMap<>();
        //用得到的wechatModel中的数据解密后获得该用户的sessionkey
        String requestUrl = "https://api.weixin.qq.com/sns/jscode2session";
        requestUrlParam.put("appid", APPID );//小程序appId
        requestUrlParam.put("secret", APPSECRET);
        requestUrlParam.put("js_code",wechatModel.getCode() );//小程序端返回的code
        requestUrlParam.put("grant_type","authorization_code" );//默认参数
        String mapToPostString = MyJsonTool.MapToPostString(requestUrlParam);
        JSONObject jsonObject = JSON.parseObject(HttpSender.sendPost(requestUrl,mapToPostString));
        String OPENID = (String) jsonObject.get("openid");
        String session_key = (String) jsonObject.get("session_key");

        if(session_key.contains("/")){
            session_key = session_key.replace("/", "");
        }
        String decrypt = decrypt(APPID, wechatModel.getEncryptedData(), (String) jsonObject.get("session_key"),wechatModel.getIv());
        JSONObject userInfo = JSON.parseObject(decrypt);

        System.out.println(userInfo);
        ZyUser user = new ZyUser();
        user.setUsername(userInfo.getString("nickName"));
        user.setOpenid(OPENID);
        user.setTime(LocalDateTime.now());
        user.setAvatar(userInfo.getString("avatarUrl"));

        user = userService.login(user);

        ValueOperations<String, String> operations = redisTemplate.opsForValue();
        operations.set(session_key, user.getId().toString());
        return session_key;
    }

    @PostMapping("/invitedLogin/{userId}")
    public String invitedLogin(@RequestBody WechatModel wechatModel, @PathVariable("userId") Integer userId) throws IOException {
        HashMap<String,String> requestUrlParam = new HashMap<>();
        //用得到的wechatModel中的数据解密后获得该用户的sessionkey
        String requestUrl = "https://api.weixin.qq.com/sns/jscode2session";
        requestUrlParam.put("appid", APPID );//小程序appId
        requestUrlParam.put("secret", APPSECRET);
        requestUrlParam.put("js_code",wechatModel.getCode() );//小程序端返回的code
        requestUrlParam.put("grant_type","authorization_code" );//默认参数
        String mapToPostString = MyJsonTool.MapToPostString(requestUrlParam);
        JSONObject jsonObject = JSON.parseObject(HttpSender.sendPost(requestUrl,mapToPostString));
        String OPENID = (String) jsonObject.get("openid");
        String session_key = (String) jsonObject.get("session_key");

        if(session_key.contains("/")){
            session_key = session_key.replace("/", "");
        }
        String decrypt = decrypt(APPID, wechatModel.getEncryptedData(), (String) jsonObject.get("session_key"),wechatModel.getIv());
        JSONObject userInfo = JSON.parseObject(decrypt);

        System.out.println(userInfo);
        ZyUser user = new ZyUser();
        user.setUsername(userInfo.getString("nickName"));
        user.setOpenid(OPENID);
        user.setTime(LocalDateTime.now());
        user.setAvatar(userInfo.getString("avatarUrl"));
        user.setFaId(userId);

        user = userService.login(user);
        ValueOperations<String, String> operations = redisTemplate.opsForValue();
        operations.set(session_key, user.getId().toString());

        //自己邀请自己
        if(user.getId().equals(userId)) return session_key;

        ZyUser invitor = userService.getById(userId);
        QueryWrapper<ZyAdmin> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", invitor.getId());
        if(adminService.getOne(wrapper) == null){
            //创建一个等级为3(经销商)的用户
            ZyAdmin admin = new ZyAdmin(null, invitor.getUsername(), "123456", 3, null, userId, null);
            adminService.save(admin);
        }


        return session_key;
    }

    @GetMapping("/getId/{session_key}")
    public Integer getInvitedId(@PathVariable("session_key") String session_key){
        Integer userId = get_userId(session_key);
        if(userId == 0) return null;
        return userId;
    }

    @GetMapping("/hello")
    public String sayHello(){
        return  "hello world!";
    }



    @PostMapping("/admin/login")
    public ZyAdmin AdminLogin(String username,String password){
        QueryWrapper<ZyUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        ZyUser res = userService.getOne(queryWrapper);
        if(res!=null){
            QueryWrapper<ZyAdmin> queryWrapperss = new QueryWrapper<>();
            queryWrapperss.eq("user_id", res.getId());
            ZyAdmin one = adminService.getOne(queryWrapperss);
            if(one!=null){
                if(password.equals(one.getPassword())){
                    //登录成功
                    redisTemplate.opsForValue().set("admin",username);
                    return one;
                }
            }
        }
        return null;
    }
    @PostMapping("/admin/logout")
    public String adminLogout(){
        redisTemplate.delete("admin");
        return "success";
    }
}
